import moment from 'moment';
import { request } from 'umi';
export const setFieldsAdaptor = (data: BasicListApi.PageData) => {
  if (data?.layout?.tabs && data.dataSource) {
    const result = {};
    data.layout.tabs.forEach((tab) => {
      tab.data.forEach((field) => {
        switch (field.type) {
          case 'datetime':
            result[field.key] = moment(data.dataSource[field.key]);
            break;
          case 'textarea':
            if (
              typeof data.dataSource[field.key] === 'object' &&
              data.dataSource[field.key] !== null
            ) {
              result[field.key] = JSON.stringify(data.dataSource[field.key]);
            } else {
              result[field.key] = data.dataSource[field.key];
            }
            break;
          case 'switch':
            result[field.key] = data.dataSource[field.key].toString() == "1";
            break;
          default:
            result[field.key] = data.dataSource[field.key];
            break;
        }
      });
    });
    return result;
  }
  return {};
};

export const submitFieldsAdaptor = (formValues: any) => {
  const result = formValues;
  Object.keys(formValues).forEach((key) => {
    if (moment.isMoment(formValues[key])) {
      result[key] = moment(formValues[key]).format();
    }
    if (Array.isArray(formValues[key])) {
      result[key] = formValues[key].map((innerValue: any) => {
        if (moment.isMoment(innerValue)) {
          return moment(innerValue).format();
        }
        return innerValue;
      });
    }
    if (typeof formValues[key] == "boolean") {
      result[key] = (formValues[key] === true ? 1 : 0);
    }
  });
  return result;
};


export function exportFile(exporturl: string, data: any, filename: string, params: any) {
  return request(exporturl, {
    method: 'POST',
    params: params,
    data: data,
    responseType: 'blob',
  }).then((res) => {
    const url = URL.createObjectURL(new Blob([res]));
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
  });
}